
package com.android.matmanual;
import java.util.List;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.net.wifi.ScanResult;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.PowerManager;
import android.os.PowerManager.WakeLock;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.WindowManager;
import android.view.View.OnClickListener;
import android.widget.LinearLayout;
import android.widget.TextView;
/**
 * @author zhangyu
 * 20120328
 */
public class WifiTest extends BaseActivity {
	public final static int WIFI_STATE_ENABLED=1;
	WifiAdmin mWifiAdmin;
//	Button closeBt;
//	Button returnBt;
	LinearLayout wifiInfo;
	boolean wifiIsStart=false;
	ProgressDialog mLoadingDialog; 
	List<ScanResult> list;
    ScanResult mScanResult;
    StringBuffer mStringBuffer = new StringBuffer();
    WakeLock mWakeLock;
    Thread mWificheck;
    Thread mWificheck2;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setTitle("wifi");
	    getWindow().setFlags(WindowManager.LayoutParams.FLAG_FORCE_NOT_FULLSCREEN, 
    	        WindowManager.LayoutParams.FLAG_FORCE_NOT_FULLSCREEN);
		setContentView(R.layout.wifi_test);
	    PowerManager pm =
		           (PowerManager) getSystemService(POWER_SERVICE); 
		    mWakeLock = pm.newWakeLock(PowerManager.SCREEN_BRIGHT_WAKE_LOCK, 
		          "XYTEST"); 
		    mWakeLock.acquire(); 
		mWifiAdmin=new WifiAdmin(WifiTest.this);
//		closeBt=(Button)findViewById(R.id.closebt);
//		returnBt=(Button)findViewById(R.id.returnbt);
		wifiInfo=(LinearLayout)findViewById(R.id.wifiinfo);
//		closeBt.setOnClickListener(this);
//		returnBt.setOnClickListener(this);
		
		mWificheck=new Thread(new Runnable() {
			public void run() {
				// TODO Auto-generated method stub

				while (mWifiAdmin.checkState()!=WifiManager.WIFI_STATE_ENABLED) {
					try {
						Thread.sleep(1000);
					} catch (InterruptedException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
				}

				wifiHandler.sendEmptyMessageDelayed(WifiTest.WIFI_STATE_ENABLED,1000); 
			}
		});
		
		mWificheck2=new Thread(new Runnable() {
			public void run() {
				// TODO Auto-generated method stub
				while (mWifiAdmin.checkState()!=WifiManager.WIFI_STATE_DISABLED) {
					try {
						Thread.sleep(1000);
					} catch (InterruptedException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
				}				
				mWifiAdmin.openWifi();
//				closeBt.setText(getResources().getString(R.string.close));
				mWificheck.start();
				wifiIsStart=true;
			}
		});
				
		if(mWifiAdmin.checkState()==WifiManager.WIFI_STATE_DISABLED){
		mWifiAdmin.openWifi();
//		closeBt.setText(getResources().getString(R.string.close));
		mLoadingDialog = ProgressDialog.show(this, "", getResources().getString(R.string.wifiopen));
		mWificheck.start();
		wifiIsStart=true;
		}
		else
		{
			mWifiAdmin.closeWifi();
			mLoadingDialog = ProgressDialog.show(this, "", getResources().getString(R.string.wifiopen));
			mWificheck2.start();
		}
	}
//	@Override
//	protected void onResume() {
//		// TODO Auto-generated method stub
//		super.onResume();
//		if(mWifiAdmin.checkState()==WifiManager.WIFI_STATE_ENABLED){
//			wifiIsStart=true;
////			closeBt.setText(getResources().getString(R.string.close));
//		}else if(mWifiAdmin.checkState()==WifiManager.WIFI_AP_STATE_DISABLED){
//			wifiIsStart=false;
////			closeBt.setText(getResources().getString(R.string.open));
//		}
//	}
	@Override
	protected void onDestroy() {
		// TODO Auto-generated method stub
		super.onDestroy();
		if(wifiIsStart){
			mWifiAdmin.closeWifi();
			wifiInfo.removeAllViews();
//			closeBt.setText(getResources().getString(R.string.open));
			wifiIsStart=false;
		}
		if(mWakeLock!=null)
		{
			mWakeLock.release(); 
			mWakeLock = null;
		}

	}
	public void getAllNetWorkList() {
        // ÿ�ε��ɨ��֮ǰ�����һ�ε�ɨ����
        if (mStringBuffer != null) {
                mStringBuffer = new StringBuffer();
        }
		Log.d("lifei", "###################### getAllNetWorkList");
        // ��ʼɨ������
        mWifiAdmin.startScan();
        list = mWifiAdmin.getWifiList();
        if (list != null) {
			
			while(list.size() == 0)
			{
				
			//	getAllNetWorkList();
				try {
						Thread.sleep(2000);
					} catch (InterruptedException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
				}
				mWifiAdmin.startScan();
				list = mWifiAdmin.getWifiList();
			}	
			Log.d("lifei", "###################### list:"+list.size());
                for (int i = 0; i < list.size(); i++) 
				{Log.d("lifei", "###################### result");
                        mScanResult = (ScanResult)list.get(i);
                    //    mStringBuffer = new StringBuffer();
                        // �õ������SSID��the network name
                        mStringBuffer = mStringBuffer
                                .append(getResources().getString(R.string.wifiaccesspoint)+(i+1)+":").append('\n')
                                .append(getResources().getString(R.string.wifiname))
                                .append(mScanResult.SSID).append('\n')
                                .append(getResources().getString(R.string.wifiaccesspointaddress))
                                .append(mScanResult.BSSID).append('\n')
                                .append(getResources().getString(R.string.wifiverificationmode))
                                .append(mScanResult.capabilities).append('\n')
                                .append(getResources().getString(R.string.wififrequency))
                                .append(mScanResult.frequency).append("MHz"+'\n')
                                .append(getResources().getString(R.string.wifisignal))
                                .append(mScanResult.level).append("dBm"+'\n')
                                .append("");
                        
					
                }
				wifiInfo.addView(returnTextView(mStringBuffer.toString()));
                mLoadingDialog.dismiss();
        }
}
	public View returnTextView(String wifiInfo){
		Log.d("lifei", "###################### returnTextView:"+wifiInfo);
		TextView wifiInfoTv = new TextView(WifiTest.this);
		wifiInfoTv.setText(wifiInfo);
		wifiInfoTv.setTextSize(20);
		return wifiInfoTv;
	}
//	public void onClick(View view) {
		// TODO Auto-generated method stub
//		int id=view.getId();
//		switch (id) {
//		case R.id.closebt:
//			if(wifiIsStart){
//				mWifiAdmin.closeWifi();
//				wifiInfo.removeAllViews();
////				closeBt.setText(getResources().getString(R.string.open));
//				wifiIsStart=false;
//			}else{
//				Thread wificheck=new Thread(new Runnable() {
//					public void run() {
//						// TODO Auto-generated method stub
//						while (mWifiAdmin.checkState()!=WifiManager.WIFI_STATE_ENABLED) {
//							try {
//								Thread.sleep(200);
//							} catch (InterruptedException e) {
//								// TODO Auto-generated catch block
//								e.printStackTrace();
//							}
//						}
//						wifiHandler.sendEmptyMessage(WifiTest.WIFI_STATE_ENABLED); 
//					}
//				});
//				if(mWifiAdmin.checkState()==WifiManager.WIFI_STATE_DISABLED){
//				mWifiAdmin.openWifi();
////				closeBt.setText(getResources().getString(R.string.close));
//				mLoadingDialog = ProgressDialog.show(this, "", getResources().getString(R.string.wifiopen));
//				wificheck.start();
//				wifiIsStart=true;
//				}
//			}
//			break;
//		case R.id.returnbt:
//			finish();
//			break;
//		default:
//			break;
//		}
//	}
	class WifiAdmin {
        private WifiManager mWifiManager;
        private WifiInfo mWifiInfo;
        private List<ScanResult> mWifiList;
        private List mWifiConfiguration;
        public WifiAdmin(Context context) {
                mWifiManager = (WifiManager) context
                                .getSystemService(Context.WIFI_SERVICE);
                mWifiInfo = mWifiManager.getConnectionInfo();
        }
        // ��WIFI
        public void openWifi() {
                if (!mWifiManager.isWifiEnabled()) {
                        mWifiManager.setWifiEnabled(true);
                }
        }
        // �ر�WIFI
        public void closeWifi() {
                if (mWifiManager.isWifiEnabled()) {
                       mWifiManager.setWifiEnabled(false);
                }
        }
        // ��鵱ǰWIFI״̬
        public int checkState() {
                return mWifiManager.getWifiState();
        }
        public void startScan() {
                mWifiManager.startScan();
                mWifiList = mWifiManager.getScanResults();
                mWifiConfiguration = mWifiManager.getConfiguredNetworks();
        }
        public List<ScanResult> getWifiList() {
                return mWifiList;
        }
   }
	
   Handler wifiHandler=new Handler(){
	   public void handleMessage(android.os.Message msg) {
		   if(msg.what==WIFI_STATE_ENABLED){
			   if(mLoadingDialog!=null){
					mLoadingDialog.dismiss();
					mLoadingDialog = ProgressDialog.show(WifiTest.this, "", getResources().getString(R.string.wificonnect));
					getAllNetWorkList();
			   }
		   }
	   }
   };
   
	@Override
	protected void onStop() {
		// TODO Auto-generated method stub
        finish();
		super.onStop();
	}
	
	
	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		int result = TestControl.GetKeyEvent(keyCode);
		if (result != TestControl.DO_NOTHING) {
			setResult(result);
			finish();
	    }
	    return true;
	}
		
}

		 